package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage());//Duplicate entry 'asd' for key 'employee.idx_username'

        if (e.getMessage().contains("Duplicate entry")) {
            //重复条目错误
            String[] s = e.getMessage().split(" ");
            String duplicate_name = s[2];
            return R.error(duplicate_name + "已被注册过了");
        }

        if (e.getMessage().contains("Column")) {
            return R.error("有字段为空,请填冲");
        }
        return R.error("其他错误");
    }



    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e) {
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }
}